/**
 * 文件单位 格式化规则： 小于1024 单位就为B  小于1024*1024 单位就位KB  小于1024*1024*1024 单位为MB, 否则为GB 至多保留两位小数
 * @param  {Number} fileSize 文件大小单位B
 */
export function fileSizeUnitFormat (fileSize) {
  let str = ''
  if (fileSize < 1024) {
    str = fileSize + 'B'
  } else if (fileSize < 1024 * 1024) {
    str = parseFloat((fileSize / 1024).toFixed(2)) + 'KB'
  } else if (fileSize < 1024 * 1024 * 1024) {
    str = parseFloat((fileSize / 1024 / 1024).toFixed(2)) + 'MB'
  } else {
    str = parseFloat((fileSize / 1024 / 1024 / 1024).toFixed(2)) + 'GB'
  }
  return str
}

/**
 * 获取 blob
 * @param  {String} url 目标文件地址
 * @return {Promise}
 */
export function getBlob (url, filename, option) {
  return new Promise((resolve, reject) => {
    const xhr = new XMLHttpRequest()
    let notification = null

    xhr.open('GET', url, true)
    xhr.responseType = 'blob'

    xhr.onload = () => {
      if (xhr.status === 200) {
        if (notification) {
          notification.message = '下载完成'

          setTimeout(() => {
            notification.close()
          }, 3000)
        }

        resolve(xhr.response)
      } else if (xhr.status >= 400) {
        if (notification) {
          notification.message = '未找到对应文件...'

          setTimeout(() => {
            notification.close()
          }, 3000)
        } else {
          reject(genError('filedown', '400'))
        }
      }
    }

    xhr.onprogress = (event) => {
      if (notification) {
        notification.message = `下载中，已下载${fileSizeUnitFormat(event.loaded)}...`
      }

      if (typeof option.progressHandler === 'function') {
        option.progressHandler()
      }
    }

    xhr.onerror = () => {
      if (notification) {
        notification.message = '下载失败'

        setTimeout(() => {
          notification.close()
        }, 3000)
      } else {
        reject(genError('filedown', '500'))
      }
    }

    if (option.showProgress !== false) {
      notification = notify({
        title: `文件下载：${filename}`,
        message: '下载开始，请稍候...',
        onClose () {
          xhr.abort()
          window.$ui.msg('下载已被取消')
        }
      })
    }

    for (const [key, value] of Object.entries(window.axios.defaults.headers.common)) {
      xhr.setRequestHeader(key, value)
    }

    xhr.send()
  })
}

/**
 * 保存
 * @param  {Blob} blob
 * @param  {String} filename 想要保存的文件名称
 */
export function saveAs (blob, filename) {
  if (window.navigator.msSaveOrOpenBlob) {
    navigator.msSaveBlob(blob, filename)
  } else {
    const link = document.createElement('a')
    const body = document.querySelector('body')

    link.href = window.URL.createObjectURL(blob)
    link.download = filename

    // fix Firefox
    link.style.display = 'none'
    body.appendChild(link)

    link.click()
    body.removeChild(link)

    window.URL.revokeObjectURL(link.href)
  }
}

/**
 * 下载
 * @param  {String} url 目标文件地址
 * @param  {String} filename 想要保存的文件名称
 */
export function download (url, filename, option) {
  return getBlob(url, filename, option).then(blob => {
    saveAs(blob, filename, option)
  })
}

export function genError (type, message) {
  return {
    type,
    message,
    fromUI: true
  }
}
export const notifications = {
  list: []
}

export const notify = function (option) {
  const notification = {
    visible: false,
    title: '系统通知',
    message: '',
    className: [],
    close () {
      this.visible = false
    }
  }

  notifications.list.push(notification)
  Object.assign(notification, option)
  notification.visible = true

  if (typeof notification.timeout === 'number') {
    setTimeout(() => {
      notification.visible = false
    }, notification.timeout)
  }

  return notification
}
